package controllers

import (
	json2 "encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"news_db/models"
)

type NewsController struct {
	beego.Controller
}

func (c *NewsController) Create() {
	var news models.News
	news.Type = c.GetString("type")
	news.Data = c.GetString("data")
	news.Title = c.GetString("title")
	news.Create()
	news.GetNewsByTitle()
	key := fmt.Sprintf("news:%d", news.ID)
	json, _ := json2.Marshal(&news)
	models.Rdb.Set(models.Ctx, key, json, -1)
	c.Data["json"] = map[string]any{"Code": 200, "Msg": "添加成功"}
	c.ServeJSON()
}
func (c *NewsController) List() {
	var newses []models.News
	keys, _ := models.Rdb.Keys(models.Ctx, "news:*").Result()
	for _, key := range keys {
		var news models.News
		json, _ := models.Rdb.Get(models.Ctx, key).Result()
		json2.Unmarshal([]byte(json), &news)
		newses = append(newses, news)
	}
	c.Data["json"] = map[string]any{"Code": 200, "Msg": "获取成功", "Data": newses}
	c.ServeJSON()
}
func (c *NewsController) Update() {
	var news models.News
	news.Type = c.GetString("type")
	news.Data = c.GetString("data")
	news.Title = c.GetString("title")
	id, _ := c.GetInt("id")
	news.ID = uint(id)
	news.Updates()
	news.GetNewsByTitle()
	key := fmt.Sprintf("news:%d", news.ID)
	json, _ := json2.Marshal(&news)
	models.Rdb.Set(models.Ctx, key, json, -1)
	c.Data["json"] = map[string]any{"Code": 200, "Msg": "修改成功"}
	c.ServeJSON()
}
func (c *NewsController) Del() {
	var news models.News
	id, _ := c.GetInt("id")
	news.ID = uint(id)
	news.Delete()
	key := fmt.Sprintf("news:%d", news.ID)
	models.Rdb.Del(models.Ctx, key)
	c.Data["json"] = map[string]any{"Code": 200, "Msg": "删除成功"}
	c.ServeJSON()
}
